<?php

$files = array();
$folder = 'upgrade';
$pattern = '*.zip';
$dir = !empty($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : 'D:\wwwroot\site1\sitestar';
//require_once('pclzip.lib.php');

// version number
$newest_vernum = '';
if( preg_match('/^([\w\. ])+$/i', urldecode($_GET['vn'])) ) {
	$guest_vernum = $_GET['vn'];
} else {
	die('Request Failed!');
}

if( file_exists("{$dir}/{$folder}.zip") ) {
	$arr_files = is_array(glob('sitestar*.zip')) ? glob('sitestar*.zip') : array();
	if (!sizeof($arr_files)) {
		if (file_exists($dir)) {
			if ($dh = opendir($dir)) {
				while (($file = readdir($dh)) !== false) {
					if (preg_match("/^sitestar\_v[0-9a-z\.\_]{1,}\.zip$/i", $file)) {
						$arr_files[] = $file;
					}
				}
				closedir($dh);
			}
		}
	}
	rsort($arr_files);
	// 2。0之前的版本禁止升级
    $arr_files2 = array();
	foreach($arr_files as $val) {
		if ($val > 'sitestar_v2.0') {
			continue;
		} else {
			$arr_files2[] = $val;
		}
	}
	$newest_vernum = basename($arr_files2[0], '.zip');
	if ($newest_vernum < $guest_vernum) $newest_vernum = $guest_vernum;
} /*else {
	$i = 0;
	$arr_lists = is_array(glob($pattern)) ? glob($pattern) : array();
	foreach( $arr_lists as $filename )
	{
		if( $guest_vernum < basename($filename, '.zip') ) {
			$files[] = $filename;
			$i++;
		}
	}

	if( $i ) {
		sort($files);
		$newest_vernum = basename($files[$i-1], '.zip');
		if( $i > 1 ) { // Older Version
			merge_folder($files, $folder);
		} else { // Neighboring Version
			copy($files[$i-1], $folder.'.zip');
		}
	} else {
		$newest_vernum = $guest_vernum;
	}
}*/
echo $newest_vernum;

function merge_folder($archives, $folder, $delfolder = '')
{
	$sql = "";
	$ln = count($archives);
	for( $i=0; $i<$ln; $i++ ) 
	{
		$unzip = new PclZip($archives[$i]);
		// unzip 
		if( $unzip->extract(PCLZIP_OPT_PATH, $folder, PCLZIP_OPT_REMOVE_PATH, $delfolder) == 0 ) {
			die("Error : ".$unzip->errorInfo(true));
		} else {
			$sql .= merge_sql( $folder );
		}
	}
	
	// update sql
	if( $handle = fopen($folder.'/basic.sql', 'wb') ) {
		fwrite($handle, $sql);
	}
	fclose($handle);
	
	// zip
	$zip = new PclZip($folder.'.zip');
	if( $zip->create($folder, PCLZIP_OPT_REMOVE_PATH, $folder) == 0 ) {
        die("Error : ".$zip->errorInfo(true));
  	} else {
  		del_dir($folder);
  	}
}

function merge_sql( $folder ) 
{
	$sql = "";
	foreach( glob($folder.'/*.sql') as $filename )
	{
		$sql .= file_get_contents($filename);
	}
	$sql .= "\r\n";
	
	return $sql;
}


function del_dir( $folder ) 
{
	foreach( glob($folder.'/*') as $filename )
	{
		if( is_dir($filename) ) { del_dir( $filename ); }
		else { unlink($filename); }
	}
	
	rmdir($folder);
}

?>